package com.shishuo.cdn.action;

import java.awt.Color;
import java.io.IOException;

import com.shishuo.cdn.util.CommonUtil;

import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shishuo.cdn.service.ApiService;
import com.shishuo.cdn.service.IdcService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
//import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.CMYKColor;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
////import com.shishuo.cdn.dao.HetongDao;
//import com.shishuo.cdn.dao.MyCdnDao;
import com.shishuo.cdn.dao.OrderDao;
import com.shishuo.cdn.dao.UserDao;
//import com.shishuo.cdn.entity.Card;
import com.shishuo.cdn.entity.User;
import com.shishuo.cdn.dao.ContractDao;
import com.shishuo.cdn.service.ContractService;
import com.shishuo.cdn.entity.ContractType;
import com.shishuo.cdn.entity.vo.JsonVo;
import com.shishuo.cdn.entity.Contract;
/**
 * 合同管理
 * @author liaoliyun
 *
 */
/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/contract")
public class ContractAction extends BaseAction {

	private static final int DEFAULT_COUNT_ONEPAGE=4;//默认每页显示条数

	
	@Autowired
	private ContractService contractService;
	
	@Autowired
	private ContractDao contractDao;

	@Autowired
	private UserDao userDao;	
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private IdcService idcService;

	@ResponseBody
	@RequestMapping(value = "/sign_contract.json", method = RequestMethod.POST)
	public JsonVo<String> sign_contract(@RequestParam(value = "contract_id") String contractId,
			HttpServletRequest request, ModelMap modelMap){	
		
		contractDao.signContract(contractId);
		Contract contract=contractDao.getContractById(contractId);
		if("newspace".equals(contract.getType()))  //签署空间租用合同
		{
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("spaceid", Integer.toString(contract.getCommodity_id()));
			map.put("status", "1");

	//		myCdnDao.modidyCdnSpaceStatus(map);
		}
		else if("speedup".equals(contract.getType()))
		{
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("cacheid", Integer.toString(contract.getCommodity_id()));
			map.put("status", "2");

		//	myCdnDao.modidyCdnCacheStatus(map);
			
		}
		else if("krxz".equals(contract.getType())) //签署扩容续租合同
		{  
			//将购买的容量和时长加到原有的租用的空间上
	//		Map<String,Object> mapSpaceMoreInfo = myCdnDao.querySpaceMoreInfoById(Integer.toString(contract.getCommodity_id()));
	//		List<Map<String, Object>> spaceList=myCdnDao.querySpaceInfo(mapSpaceMoreInfo);
	//		Map<String, Object> space=spaceList.get(0);
	//		space.put("tot_volume", Integer.valueOf(space.get("tot_volume").toString())+Integer.valueOf(mapSpaceMoreInfo.get("tot_volume").toString()));//增加空间容量 Integer.valueOf(tempParams[0])
	//		double	 addMoney=Double.valueOf((mapSpaceMoreInfo.get("cost_money").toString()));
	//		 String[] tempParams=dealFeeParams(Integer.valueOf(mapSpaceMoreInfo.get("tot_volume").toString()),Integer.valueOf(mapSpaceMoreInfo.get("buy_num").toString())).split("-");//空间单价 每M每月-赠送月数
	//		 space.put("tot_volume", Integer.valueOf(space.get("tot_volume").toString())+Integer.valueOf(mapSpaceMoreInfo.get("tot_volume").toString()));//增加空间容量 Integer.valueOf(tempParams[0])
	//		 space.put("buy_num", Integer.valueOf(space.get("buy_num").toString())+Integer.valueOf(mapSpaceMoreInfo.get("buy_num").toString()));//购物数量
	//		 space.put("give_num", Integer.valueOf(space.get("give_num")==null?"0":space.get("give_num").toString())+Double.valueOf(tempParams[1]));//赠送数量
	//		 space.put("end_time", CommonUtil.addMonthes(space.get("end_time").toString(), Integer.valueOf(mapSpaceMoreInfo.get("buy_num").toString()))) ;
	//		 double oldMoney=Double.valueOf(space.get("cost_money").toString());
	//		 myCdnDao.modifySpaceInfo(space);
			 
			 Map<String, Object> map = new HashMap<String,Object>(); 
	//		 map.put("space_name", space.get("space_id"));
	//		 map.put("storage_limit",space.get("tot_volume"));
			 ApiService.createOrModifySpace(map,"modify");//调用清华接口

		}
		json.setResult(true);
				
		return json;
	}
	//取消合同操作，by liaoliyun 
	@ResponseBody
	@RequestMapping(value = "/concel_contract.json", method = RequestMethod.POST)
	public JsonVo<String> concel_contract(@RequestParam(value = "contract_id") String contractId,
			HttpServletRequest request, ModelMap modelMap){	
		double balance=0;
		Contract contract=contractDao.getContractById(contractId);
		refreshSessionUser(request);//刷新session里的user 拿到最新余额
		User user=(User)request.getSession().getAttribute("user");
		user=userDao.getUserById(user.getReg_tel());
        
	    Map<String,Object> map = new HashMap<String,Object>();

		if("newspace".equals(contract.getType()))  //空间租用合同
		{
			//先退款
			
//	        balance= Double.valueOf(user.getBalance().toString()) + Double.valueOf(myCdnDao.queryCdnSpaceCostById(Integer.toString(contract.getCommodity_id())));
			//删除未生效的租用空间
//			myCdnDao.deleteCdnSpaceById(Integer.toString(contract.getCommodity_id()));
		}
		else if("speedup".equals(contract.getType())) //加速合同
		{
//	        balance= Double.valueOf(user.getBalance().toString()) + Double.valueOf(myCdnDao.queryCdnCacheCostById(Integer.toString(contract.getCommodity_id())));
//			myCdnDao.deleteCdnCacheById(Integer.toString(contract.getCommodity_id()));

		}
		else if("krxz".equals(contract.getType()))
		{
//			Map<String,Object> mapSpaceMoreInfo = myCdnDao.querySpaceMoreInfoById(Integer.toString(contract.getCommodity_id()));
//			balance = Double.valueOf(user.getBalance().toString()) +Double.valueOf(mapSpaceMoreInfo.get("cost_money").toString()); 
//			myCdnDao.deleteCdnSpaceMoreById(Integer.toString(contract.getCommodity_id()));		
		}
        user.setBalance(new BigDecimal(balance));//更新用户余额	       
		map.put("balance", balance);
		map.put("userId", user.getUser_id());
		userDao.updateBalanceById(map);
		
		//删除合同
		contractDao.concelContract(contractId);
		
		json.setResult(true);
				
		return json;
	}	
	
	
	@ResponseBody
	@RequestMapping(value = "/addcontract.json", method = RequestMethod.POST)
	public JsonVo<String> addcontract(@RequestParam(value = "contract_type") String contractType,
			@RequestParam(value = "commodityId") String commodityId,@RequestParam(value = "hetong") String hetong,
			HttpServletRequest request, ModelMap modelMap){	
		
		String Contract_num=null;
		Map<String,Object> orderInfo = new HashMap<String,Object>();
		
		User user=(User)request.getSession().getAttribute("user");
		user=userDao.getUserById(user.getReg_tel());
//		paramsMap.put("start_time", new Date());
		if("ISP".equals(contractType))
		{
			orderInfo = orderDao.queryISPOrderById(commodityId);
			
			Contract_num =user.getReg_tel() +"ISP"+commodityId;  //生成合同编号
			
			paramsMap.put("status", 3); //将订单状态改为生效状态
			paramsMap.put("order_id", commodityId);
			
			
			orderDao.updateISPOrderStatus( paramsMap);
			
		}
		else if("IDC".equals(contractType))
		{
			orderInfo = orderDao.queryIDCOrderById(commodityId);
			Contract_num =user.getReg_tel() +"IDC"+commodityId;  //生成合同编号
			
			paramsMap.put("status", 3); //将订单状态改为生效状态
			paramsMap.put("order_id", commodityId);
			
			orderDao.updateIDCOrderStatus( paramsMap);
			
		}
	    
		Contract contract = new Contract();
		contract.setStart_time(new Date());
		contract.setEnd_time(CommonUtil.addMonthes(CommonUtil.getNowDate().toString(),Integer.valueOf(orderInfo.get("order_span").toString())*12));
		contract.setType(contractType);
		contract.setUser(user.getReg_tel());
		contract.setContract_bianhao(Contract_num);
		contract.setCommodity_id(Integer.parseInt(commodityId));
		contract.setHt_content(hetong);
		contractDao.addContract(contract);
		json.setResult(true);
		return json;
	}
  
	@RequestMapping(value="/contractcancel.htm",method = RequestMethod.GET)
	public String contractcancel(HttpServletRequest request,ModelMap modelMap){
		json.setResult(true);
		return "/business/questionnaire";
	}
     
	@ResponseBody
	@RequestMapping(value="/investigation.json",method = RequestMethod.POST)
	public JsonVo<String> investigation(HttpServletRequest request,ModelMap modelMap){
		return json;
	}
	
	@RequestMapping(value="/contractadmin.htm",method = RequestMethod.GET)
	public String contractadmin(HttpServletRequest request,ModelMap modelMap)throws Exception{
		Date date;
		int pages=0;
		int offset=0;
		int totalCount=0;
		User user=(User)request.getSession().getAttribute("user");
		createParameterMap(request);
		int pageNo=paramsMap.get("pageNo")!=null?Integer.valueOf(paramsMap.get("pageNo").toString()):1;
//		-------分页查询
		pageNo=pageNo<1?1:pageNo;//页码当前为1
		paramsMap.put("user_id", user.getReg_tel());
		if("".equals(paramsMap.get("type")) || null==paramsMap.get("type") || "0".equals(paramsMap.get("type").toString())){
			paramsMap.remove("type");//""查询全部
		}else{
			paramsMap.put("type", paramsMap.get("type"));
		}
		
		if(!"".equals(paramsMap.get("start_date1")) && null != paramsMap.get("start_date1"))
		{
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH/mm/ss");

			paramsMap.put("start_date", sdf.parse(paramsMap.get("start_date1").toString()+" 00/00/00")) ;			
		}
		if(!"".equals(paramsMap.get("end_date1")) && null != paramsMap.get("end_date1") )
		{
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH/mm/ss");
			
			paramsMap.put("end_date", sdf.parse(paramsMap.get("end_date1").toString()+" 23/59/59")) ;			
		}

		
		 totalCount = contractDao.queryContractCount(paramsMap);//记录总数
		//总页数
		 pages=totalCount%DEFAULT_COUNT_ONEPAGE==0?totalCount/DEFAULT_COUNT_ONEPAGE:totalCount/DEFAULT_COUNT_ONEPAGE+1;
//		if(pageNo<1) pageNo=1;
		if(pageNo>pages) pageNo=pages;
		 offset=(pageNo-1)*DEFAULT_COUNT_ONEPAGE;//偏移量
		
		if(offset<0)offset=0;
		paramsMap.put("offset", offset);
		paramsMap.put("rows", DEFAULT_COUNT_ONEPAGE);
		
		List<Map<String,Object>>   contractInfoList = contractDao.queryContractInfo(paramsMap);
		
		modelMap.addAttribute("contractInfoList", contractInfoList);//用户的合同列表信息
		modelMap.put("pages",pages);//总页数
		modelMap.put("totalCount", totalCount);//总条数
		modelMap.put("pageNo", pageNo);//当前页号
		paramsMap.remove("pageNo");
		modelMap.putAll(paramsMap);

		return "/business/contractadmin";
	
	}

	@RequestMapping(value="/contractView.htm",method = RequestMethod.GET)
	public String contractView(HttpServletRequest request,ModelMap modelMap,
			@RequestParam(value = "id") String contractId){
		Contract contract=contractDao.getContractById(contractId);
		String content = contractDao.queryContractContent(contract.getType());
		modelMap.put("contract", content);
		return "/business/contractview";
	}
	
	@RequestMapping(value="/contractPage.htm",method = RequestMethod.GET)
	public String hetongPage(HttpServletRequest request,ModelMap modelMap,
			@RequestParam(value = "ordertype") String contracttype,@RequestParam(value = "orderid") String Id) throws ParseException{
		createParameterMap(request);

		ContractType contractType = contractService.getContractTypeByType(contracttype);
		String contract_content = contractType.getContent();
		User user=(User)request.getSession().getAttribute("user");
		if("null".equals(user.getCompany())||null==user.getCompany()){
			user.setCompany("");
		}
		if("null".equals(user.getDh())||null==user.getDh()){
			user.setDh("");
		}
		if("null".equals(user.getReal_name())||null==user.getReal_name()){
			user.setReal_name("");
		}
		if("ISP".equals(contracttype)){
			//ISP合同
			Map<String,Object> map=orderDao.queryISPOrderById(Id);
			contract_content=replaceISPContent(map,contract_content);
		}else{
			//IDC合同
			Map<String,Object> map=orderDao.queryIDCOrderById(Id);
			contract_content=replaceIDCContent(map,contract_content);
		}
		modelMap.put("userinfo", user);
		modelMap.put("contract_content", contract_content);
		modelMap.put("contracttype", contracttype);
		modelMap.put("commodityid", Id);
		
/*		if("null".equals(contractid))
		{
			String contract_num=null;
		
			user=userDao.getUserById(user.getReg_tel());
			if("newspace".equals(contracttype))
			{
				contract_num =user.getReg_tel() +'K'+Id;  //生成合同编号
			}
			else if("speedup".equals(contracttype))
			{
				contract_num =user.getReg_tel() +'S'+Id;  //生成合同编号
			}
			else if("krxz".equals(contracttype))
			{
				contract_num =user.getReg_tel() +'M'+Id;  //生成合同编号
			}
			Contract contract = new Contract();
			contract.setType(contracttype);
			contract.setUser(user.getReg_tel());
			contract.setIfSigned((byte)Integer.parseInt("0"));
			contract.setContract_bianhao(contract_num);
			contract.setCommodity_id(Integer.parseInt(Id));
			contractDao.addContract(contract);
			modelMap.put("contract", contract);
		}
		else
		{
			Contract contract=contractDao.getContractById(contractid);
			modelMap.put("contract", contract);
		}
*/
		return "/business/contract";
	}
	
	/**
	 * 
	 * 描述：ISP合同内容替换
	 * 创建人： 魏泽超
	 * 创建时间: 2016-3-31 下午4:02:42
	 * @version
	 */
	private String replaceISPContent(Map<String,Object> map,String content) throws ParseException{
		String jfStrReplace=content.replace("<yflianxiren>", "网视通联").replace("<yfdh>", "029-5555").replace("<yfaddress>", "北京市知春路大钟寺");
		String yfStrReplace=jfStrReplace.replace("<jflianxiren>", map.get("user_name").toString()).replace("<jfaddress>", map.get("user_addr").toString()+map.get("user_addr2").toString()+map.get("user_addr3").toString()).replace("<jfdh>", map.get("user_phone").toString());
		String typeReplace=yfStrReplace.replace("<xianlu>", Integer.valueOf(map.get("ISP_type").toString())==1?"单线":"双线").replace("<daikuan>", map.get("ISP_speed").toString()+"M");
		//System.out.println(Integer.valueOf(map.get("ISP_type").toString())==1?"单线":"双线"+" -----------"+map.get("ISP_type").toString());
		SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
		Date old=sd.parse(map.get("start_time").toString());
		String startTime=sdf.format(old);
//		Calendar curr = Calendar.getInstance();
//		curr.setTime(old);
//		curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+Integer.valueOf(map.get("order_span").toString()));
//		Date date=curr.getTime();
//		String endTime=sdf.format(date);
//		String timeReplace=typeReplace.replace("<startTime>", startTime).replace("<endTime>", endTime).replace("<month>", Integer.valueOf(map.get("order_span").toString())*12+"");
		String timeReplace=typeReplace.replace("<startTime>", startTime).replace("<month>", Integer.valueOf(map.get("order_span").toString())*12+"");
		String newContent=timeReplace.replace("<feiyong>", map.get("cost_money").toString()).replace("<freeip>", map.get("free_IP").toString()).replace("<buyip>", map.get("buy_IP").toString());
		return newContent;
	}
	
	/**
	 * 
	 * 描述：IDC合同内容替换
	 * 创建人： 魏泽超
	 * 创建时间: 2016-4-1 上午10:13:13
	 * @version
	 */
	private String replaceIDCContent(Map<String,Object> map,String content) throws ParseException{
		String jfStrReplace=content.replace("<yflianxiren>", "网视通联").replace("<yfdh>", "029-5555").replace("<yfaddress>", "北京市知春路大钟寺");
		String yfStrReplace=jfStrReplace.replace("<jflianxiren>", map.get("user_name").toString()).replace("<jfaddress>", map.get("user_addr").toString()+map.get("user_addr2").toString()+map.get("user_addr3").toString()).replace("<jfdh>", map.get("user_phone").toString());
		String typeReplace=yfStrReplace.replace("<xianlu>", Integer.valueOf(map.get("speed_type").toString())==1?"单线":"双线").replace("<daikuan>", map.get("IDC_speed").toString()+"M").replace("<IDCtype>", Integer.valueOf(map.get("IDC_type").toString())==0?"机柜":"机架").replace("<IDCCount>", Integer.valueOf(map.get("IDC_type").toString())==0?"使用机柜尺寸："+map.get("jigui_type").toString():"使用机架为："+map.get("jijia_count").toString()+"U");
		//System.out.println(Integer.valueOf(map.get("ISP_type").toString())==1?"单线":"双线"+" -----------"+map.get("ISP_type").toString());
		SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
		Date old=sd.parse(map.get("start_time").toString());
		String startTime=sdf.format(old);
		//Calendar curr = Calendar.getInstance();
		//curr.setTime(old);
		//curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+Integer.valueOf(map.get("order_span").toString()));
		//Date date=curr.getTime();
		//String endTime=sdf.format(date);
//		String timeReplace=typeReplace.replace("<startTime>", startTime).replace("<endTime>", endTime).replace("<month>", Integer.valueOf(map.get("order_span").toString())*12+"");
		String IPPrice=idcService.getPrice("IP");
		String timeReplace=typeReplace.replace("<startTime>", startTime).replace("<month>", Integer.valueOf(map.get("order_span").toString())+"").replace("<IPPrice>", IPPrice).replace("<IPCount>", Integer.valueOf(map.get("buy_IP").toString())*Integer.valueOf(IPPrice)+"");
		String newContent=timeReplace.replace("<feiyong>", map.get("cost_money").toString()).replace("<freeip>", map.get("free_IP").toString()).replace("<buyip>", map.get("buy_IP").toString());
		return newContent;
	}
	
	@RequestMapping(value = "/contractDown.htm", method = RequestMethod.GET)
	public String hetong(HttpServletRequest request, HttpServletResponse response) throws DocumentException, MalformedURLException, IOException, ParseException { 
		createParameterMap(request);
		//从session得到用户信息
 		User user = (User) request.getSession().getAttribute("user");
 		String type=request.getParameter("type");
 		Map<String,Object> param=new HashMap<String,Object>();
 		param.put("user_id", user.getReg_tel());
 		List<Map<String,Object>> map=null;
 		if("ISP".equals(type)){
 			map=orderDao.queryISPOrderByUserId(param);
 		}else{
 			map=orderDao.queryIDCOrderByUserId(param);
 		}
 		String downName=map.get(0).get("order_num").toString()+"_"+map.get(0).get("type").toString()+"_"+map.get(0).get("user_id").toString();
//		System.out.println(paramsMap);
		// Listing 1. Instantiation of document object
		Document document = new Document(PageSize.A4, 50, 50, 50, 50);
		String id=request.getParameter("id");
		
		 response.setContentType("application/pdf");
		 response.setHeader("Content-Disposition", "attachment;filename=\""+downName+".pdf\"");  
		
		// Listing 2. Creation of PdfWriter object
		PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());

		document.open();
		
 		 
 		Contract contract=contractDao.getContractById(id);
 		if(!user.getReg_tel().equals(contract.getUser())){
 			return null;
 		}
 		
 	//	 Paragraph title11 = new Paragraph("公司名称："+paramsMap.get("company")+"       乙方：北京网视通联科技有限公司",fontChinese);
 	//	 chapter1.add(title11);
 	//	title11 = new Paragraph("手机："+paramsMap.get("telephone")+"       联系人："+paramsMap.get("realname"),fontChinese);
 	//	chapter1.add(title11);
//		 Section chapter1 = chapter1.addSection(title11);
         //Paragraph pf = new Paragraph("甲方租用乙方提供的CDN加速服务和空间存储服务。甲乙双方经友好协商，现就相关事宜，订立本协议，以资遵行。",fontChinese);
         //chapter1.add(pf);
         //pf.setFirstLineIndent(25);
         /*pf = new Paragraph("第一条 甲方承诺严格遵守《中华人民共和国计算机信息网络国际联网暂行规定》、《 互联网信息服务管理办法》、《计算机信息网络国际联网安全保护管理办法》、《互联网电子公告服务管理规定》等有关法律、法规和行政规章等规定，不得利用所租用的服务从事危害国家安全、泄漏国家秘密、违法犯罪、妨碍社会治安的活动，不得损害第三人的合法权益。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第二条  甲方承诺遵守信息产业部第33号令的要求，如实填写网站备案信息表，依法履行备案义务。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第三条  甲方向乙方提出服务申请时，应当签订有关的服务订单，服务订单生效后，乙方在 1 个工作日内为甲方提供所租用的服务。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第四条  在协议有效期内，甲方保证其向乙方提供的资料真实、有效，并保证在发生任何变更后 5 个工作日内以书面形式通知乙方。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第五条  因甲方原因或不可抗力造成有关的软件、数据库和类似的设置等的损坏，乙方不负任何责任。乙方应根据与甲方签订的服务订单，为其提供有关的系统运行维护、故障排除等相关基本服务和其他约定的服务。在此甲方认同：由于不可抗力而造成的线路中断或甲方的访问速率下降，乙方将不负任何责任。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第六条  如果甲方在使用本合同项下服务时遭遇黑客攻击、病毒感染等情况，已经影响乙方的其他用户的正常使用，乙方有权立即终止向甲方提供服务，并随即通知甲方，待甲方已经完全解除黑客攻击、病毒感染等情况，乙方再行恢复服务，在此种情形下，乙方无须承担任何赔偿责任。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第七条  如果甲方在使用本合同项下服务时违反有关法律、法规、行政规章等规定，乙方有权通知甲方在一定时间内改正，或视情况立即中止向甲方提供相关服务，直至部分或全部解除合同，并有权依法保存有关记录，向政府主管部门报告，由此引起的一切后果和责任均由甲方承担。而乙方无须承担任何赔偿责任。如有关主管部门向乙方下达涉及本合同项下的服务的禁令或类似要求，乙方可立即予以执行，但应同时告知甲方，在甲方查找原因及时纠正后再行恢复服务，在此种情形下，乙方无须承担任何赔偿责任。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第八条  乙方因检修线路、设备搬迁、工程割接、网络及软件升级等可预见的原因影响或可能影响甲方使用服务的，应提前72小时通知甲方的联系人。若甲方提供的信息错误或联系人变更未及时通知乙方而造成延误的，乙方不承担责任。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第九条  乙方提供的服务具体标准满足信息产业部颁布的《电信服务质量标准》，保证甲方使用通信业务安全畅通，乙方在工作时间内随时为甲方以电话、传真、电子邮件等方式免费提供所买服务，提供实时响应解决。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第十条  任何一方未履行本协议的任何一项条款均被视为违约。在此情形下,甲乙双方可就此问题进行协商,协商不成的,应向北京仲裁委员会申请仲裁。合同任何一方不得擅自解除或终止本合同，否则视为违约。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第十一条  任何一方未经对方事先书面同意，不得转让本协议的任何一项权利和义务。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第十二条  甲乙双方对彼此之间相互提供的信息、资料以及本协议的具体内容负有保密责任。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第十三条  因不可抗力导致甲乙双方或一方不能履行或不能完全履行本协议有关义务时，双方相互不承担违约责任。但遇有不可抗力的一方或双方应于不可抗力发生后15日内将情况告知对方，并提供有关部门的证明。在不可抗力影响消除后的合理时间内，一方或双方应当继续履行合同。不可抗力事件包括严重自然灾害、政府行为、第三方服务故障等不可抗拒的事件。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);
         pf = new Paragraph("第十四条  本协议自甲方确认同意之日起生效。",fontChinese);
         chapter1.add(pf);
         pf.setFirstLineIndent(25);*/
         
         
        String classPath = request.getSession().getServletContext().getRealPath("/");
        map=contractDao.queryContractInfo(param);
        if("ISP".equals(type)){
        	setPdf(contract.getHt_content(),document,classPath,map.get(0).get("start_time").toString(),"ISP");
        }else{
        	setPdf(contract.getHt_content(),document,classPath,map.get(0).get("start_time").toString(),"IDC");
        }
        
		return null;
	}
	
	
	/**
	 * 
	 * 描述：设置pdf内容
	 * 创建人： 魏泽超
	 * 创建时间: 2016-3-31 下午5:10:22
	 * @version
	 * @throws ParseException 
	 */
	private void setPdf(String hetong,Document document,String classPath,String time,String type) throws DocumentException, IOException, ParseException{
		SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
		Date old=sd.parse(time);
		String startTime=sdf.format(old);
		String replaceStr="";
		if("ISP".equals(type)){
			replaceStr=hetong.replace("<p>", "").replace("<p class=\"colR f17\">", "").replace("<center>", "").replace("<font size=\"+3\" color=\"red\">","").replace("<font color=\"red\" size=\"+3\">","").replace("</center>", "").replace("<p id=\"effectTime\">", "                        合同签署时间："+startTime).replace("</font>","</p>");
		}else{
			replaceStr=hetong.replace("<p>", "").replace("<p class=\"colR f17\">", "").replace("<center>", "").replace("<font size=\"+3\" color=\"red\">","").replace("<font color=\"red\" size=\"+3\">","").replace("</center>", "").replace("<p id=\"effectTime\">", "合同签署时间："+startTime).replace("</font>","</p>");
		}
		String[] str=replaceStr.split("</p>");
		BaseFont bfChinese = BaseFont.createFont( "STSongStd-Light" ,  "UniGB-UCS2-H" ,  false );   
        Font titleFont =  new Font(bfChinese,20,Font.BOLD); 
        Font fontChinese =  new Font(bfChinese,12,Font.BOLD); 
		Chapter chapter1 = new Chapter(1);
		Paragraph pf = new Paragraph();
		for (int i = 0; i < str.length; i++) {
			if(0==i){
				pf=new Paragraph(str[i].replace(" ", ""),titleFont);
				pf.setAlignment(Element.ALIGN_CENTER);
				chapter1.add(pf);
		        pf.setFirstLineIndent(25);
			}else{
				pf = new Paragraph(str[i],fontChinese);
				chapter1.add(pf);
		        pf.setFirstLineIndent(25);
			}
		}
		Image image2 = Image.getInstance(classPath+"wsgz.gif");
 		image2.scaleAbsolute(120f, 120f);
 		image2.setAlignment(Element.ALIGN_LEFT);
 		chapter1.add(image2);
		document.add(chapter1);
		document.close();
	}
	/**
	 * 
	 * 描述：合同查看
	 * 创建人： 魏泽超
	 * 创建时间: 2016-3-31 下午5:37:07
	 * @version
	 */
	@ResponseBody
	@RequestMapping(value="/hetongView.json",method = RequestMethod.POST)
	public Map<String,Object> hetongView(HttpServletRequest request,ModelMap modelMap,
			@RequestParam(value = "id") String Id) throws ParseException{
		createParameterMap(request);
		Map<String,Object> json=new HashMap<String,Object>();
		//从session得到用户信息
 		User user = (User) request.getSession().getAttribute("user");
 		Contract contract=contractDao.getContractById(Id);
 		if(!user.getReg_tel().equals(contract.getUser())){
 			json.put("status", "0");
 			json.put("info", "查看合同失败");
 			return json;
 		}
 		if(null!=contract.getHt_content() && !("").equals(contract.getHt_content())){
 			json.put("status", "1");
 			json.put("info", contract.getHt_content());
 		}
		return json;
	}
	
	private String dealFeeParams(int space,int months){
		StringBuffer sb=new StringBuffer();
//		 List<Map<String, Object>> cckj=myCdnDao.queryFeeParams("cunchu_kongjian");
//		 List<Map<String, Object>> jfzq=myCdnDao.queryFeeParams("jifei_zhouqi");
//		 for(Map one:cckj)
//			 if(Integer.valueOf(one.get("min_value").toString())<=space &&Integer.valueOf(one.get("max_value").toString())>=space)
//			 {
//				 sb.append(one.get("unit_price"));sb.append("-");
//				 break;
//			 }
//		 for(Map one:jfzq)
//			 if(Integer.valueOf(one.get("min_value").toString())<=months &&Integer.valueOf(one.get("max_value").toString())>=months)
//			 {
//				 sb.append(one.get("unit_price"));
//				 break;
//			 }
		 return sb.toString();//空间单价 每M每月-赠送月数
	}	
//	@ResponseBody
//	@RequestMapping(value = "/validate.htm", method = RequestMethod.POST)
//	public String validate(@RequestParam(value = "name") String name,
//			@RequestParam(value = "tel") String tel,
//			@RequestParam(value = "lx_name") String lx_name,
//			@RequestParam(value = "user_id") String user_id,
//			HttpServletRequest request, HttpServletResponse response){
//			Card card = hetongDao.getCardById(user_id);
//			if(null == card){
//				card.setCompany(name);
//				card.setUser_id(Integer.parseInt(user_id));
//				hetongDao.addCard(card);
//			}else{
//				card.setCompany(name);
//				hetongDao.updateCard(card);
//			}
//			
//		return "";
//	}
}
